package cool.mtc.security.handler.auth;

import cool.mtc.security.auth.AuthToken;
import cool.mtc.security.constant.SecurityConstant;
import cool.mtc.security.handler.HandleSupport;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 明河
 */
public abstract class AuthSuccessHandler extends AuthHandler implements HandleSupport, AuthenticationSuccessHandler {

    public void success(Authentication authentication) {
        AuthToken authToken = (AuthToken) authentication;

        // token放入响应头中
        this.setTokenToResponseHeader(authToken.getToken());

        this.responseData(authToken.getToken());
    }

    public void setTokenToResponseHeader(String token) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        assert response != null;
        response.addHeader(SecurityConstant.PARAM_TOKEN_KEY, token);
    }

}
